package com.xmall.service.util;

import com.sun.istack.internal.NotNull;
import com.xmall.bean.table.*;
import com.xmall.bean.vo.BaseCouponRespVO;
import com.xmall.mapper.*;


import java.util.Date;
import java.util.List;

/**
 * @author Connor
 * @ClassName: CouponUtils
 * @PackageName: com.xmall.service.util
 * @date 2020/12/10
 * @Version 1.0
 */
public class CouponUtils {

    @NotNull
    public static Boolean hasCoupon(Integer cartId, @NotNull Coupon coupon, CartMapper cartMapper, GoodsMapper goodsMapper, CategoryMapper categoryMapper, Integer userId) {
        // 判断优惠券使用范围
        if (coupon.getGoodsType() == 2) {
            Integer count = null;
            for (Integer goodsId : coupon.getGoodsValue()) {
                // 从商品页面直接下单
                if (cartId != 0) {
                    Cart cart = cartMapper.selectByPrimaryKey(cartId);
                    Integer cartGoodsId = cart.getGoodsId();
                    Integer price = cart.getPrice().intValue();
                    Integer number = cart.getNumber().intValue();
                    // TODO 判断满减条件
                    if (goodsId.equals(cartGoodsId) && price * number > coupon.getMin().intValue()) {
                        count++;
                    }
                }
                // 从购物车下单
                List<Cart> cartList = getCarts(cartMapper, userId);
                for (Cart cart : cartList) {
                    Integer totalPrice = null;
                    if (goodsId.equals(cart.getGoodsId())) {
                        Integer price = cart.getPrice().intValue();
                        Integer number = cart.getNumber().intValue();
                        totalPrice = totalPrice + price * number;
                        // TODO 如果购物车中只有部分商品满足优惠券的使用条件，应该将这些商品挑选出来
                    }
                    if (totalPrice > coupon.getMin().intValue()) {
                        count++;
                    }
                }
            }
            if (count == null) {
                // TODO 没有可用优惠券
                return false;
            }
        }
        if (coupon.getGoodsType() == 1) {
            Integer count = null;
            for (Integer categoryId : coupon.getGoodsValue()) {
                if (cartId != 0){
                    Cart cart = cartMapper.selectByPrimaryKey(cartId);
                    count = getICount(goodsMapper, categoryMapper, count, categoryId, cart);
                }
                List<Cart> cartList = getCarts(cartMapper, userId);
                for (Cart cart : cartList) {
                    count = getICount(goodsMapper, categoryMapper, count, categoryId, cart);
                }
            }
            if (count == null) {
                return false;
            }
        }
        // TODO 判断团购条件（grouponRulesId）
        return true;
    }

    public static Integer getICount(@NotNull GoodsMapper goodsMapper, @NotNull CategoryMapper categoryMapper, Integer count, @NotNull Integer categoryId, @NotNull Cart cart) {
        Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
        Category category = categoryMapper.selectByPrimaryKey(goods.getCategoryId());
        if (categoryId.equals(category.getId())) {
            count++;
        }
        return count;
    }

    public static List<Cart> getCarts(@NotNull CartMapper cartMapper, Integer userId) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria1 = cartExample.createCriteria();
        criteria1.andUserIdEqualTo(userId);
        criteria1.andCheckedEqualTo(true);
        criteria1.andDeletedEqualTo(false);
        return cartMapper.selectByExample(cartExample);
    }

    @NotNull
    public static Integer InsertCoupon(@NotNull Coupon coupon, Integer couponAmount, CouponUserMapper couponUserMapper, Integer userId, Integer couponId, CouponMapper couponMapper) {
        Date startTime = null;
        Date endTime = null;
        if (coupon.getStatus() != 0) {
            // 优惠券状态，如果是0则是正常可用；如果是1则是过期; 如果是2则是下架。
            // 优惠券不可用，过期或下架
            return 100;
        }
        if (coupon.getTotal() < 0) {
            // 优惠券已经领完
            return 200;
        }
        if (coupon.getLimit() < 0) {
            // TODO 异常处理，用户领券限制数量不能小于0
            return 500;
        }
        if (!(coupon.getLimit() == 0 || coupon.getLimit() > couponAmount)) {
            // 优惠券已经领取过或者已达领取上限
            return 300;
        }
        // 用户领券不限制数量，或者用户领券还未到达上限（couponAmount为已领券数量，>=0）。
        // TODO 插入
        if (coupon.getTimeType() == 0) {
            // time_type(有效时间限制)，如果是0，则基于领取时间的有效天数days；
            startTime = new Date();
            endTime = new Date(startTime.getTime() + coupon.getDays() * 24 * 60 * 60 * 1000);
        } else if (coupon.getTimeType() == 1) {
            // 如果是1，则start_time和end_time是优惠券有效期；
            startTime = coupon.getStartTime();
            endTime = coupon.getEndTime();
        }
        couponUserMapper.insertSelective(new CouponUser(null,
                userId,
                coupon.getId(),
                Short.valueOf("0"),
                null,
                startTime,
                endTime,
                null,
                new Date(),
                new Date(),
                false));
        if (coupon.getTotal() != 0) {
            Coupon coupon1 = new Coupon();
            coupon1.setId(couponId);
            if (coupon.getTotal() - 1 == 0) {
                // 限量优惠券限量领取后数量自动，减到0时变成一个负数
                coupon1.setTotal(-1);
            } else {
                coupon1.setTotal(coupon.getTotal() - 1);
            }
            couponMapper.updateByPrimaryKeySelective(coupon1);
        }
        return 0;
    }
}
